<template>
  <view>
    <view class="head">
      <view class="search-bar">
        <u-search @change="search()" @search="search()" @clear="clear()" v-model="keyword" shape="round" clearabled
                  :show-action="false" placeholder="请输入用户名...">
        </u-search>
      </view>
      <view>
        <u-button @click="navigate2UserAdd" :custom-style="{border:'none'}" :hairline="false" icon="plus-circle"
                  size="large">
        </u-button>
      </view>
    </view>
    <u-index-list :index-list="list.userIndex">
      <template v-for="(users, index) in list.userInfo">
        <u-index-item>
          <u-index-anchor height="20" :text="list.userIndex[index]"></u-index-anchor>
          <view class="common" v-for="user in users">
            <u--form>
              <u-form-item @click="navigate2UserUpdate(user)" border-bottom>
                <u-input
                    :value="user.name"
                    disabled
                    disabledColor="#fff"
                    border="none">
                  <template slot="prefix">
                    <u-avatar :custom-style="{'margin-right':'10px'}" shape="square" :src="user.avatar"></u-avatar>
                  </template>
                  <template slot="suffix">
                    <u-icon name="arrow-right"></u-icon>
                  </template>
                </u-input>
                <u-icon slot="right" color="#fff" name="arrow-right"></u-icon>
              </u-form-item>
            </u--form>
          </view>
        </u-index-item>
      </template>
    </u-index-list>
  </view>
</template>

<script>
import {getGroupByPinyin} from '@/common/pinyin/utils'

export default {
  onShow() {
    this.getAllUsers()
  },
  data() {
    return {
      keyword: '',
      users: [],
      curUsers: [],
      list: {}
    }
  },
  methods: {
    async getAllUsers() {
      this.users = this.curUsers = (await uniCloud.database().collection('user').get()).result.data
      await this.updateData()
    },
    updateData() {
      let users = getGroupByPinyin(this.curUsers, 'name')
      this.list.userIndex = users.map(user => user.name)
      this.list.userInfo = users.map(user => user.value)
    },
    search(value) {
      this.curUsers = this.users.filter(item => item.name.indexOf(value, 0) !== -1)
      this.updateData()
    },
    clear() {
      this.keyword = ''
    },
    // 使用type字段表示新增或修改 0-新增 1-修改
    navigate2UserAdd() {
      uni.navigateTo({
        url: './UserAddOrUpdate?type=0'
      })
    },
    navigate2UserUpdate(user) {
      uni.navigateTo({
        url: `./UserAddOrUpdate?type=1&user=${JSON.stringify(user)}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.head {
  margin-left: 20px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;

  .search-bar {
    width: 100%;
  }
}

</style>
